<template>
  <div class="role-container">
    <el-card class="operation-card">
      <div class="operation-area">
        <!-- 左侧按钮区域 -->
        <div class="operation-buttons">
          <el-button type="primary" @click="handleAdd">
            <el-icon><Plus /></el-icon> 新增角色
          </el-button>
        </div>

        <!-- 右侧搜索区域 -->
        <div class="search-container">
          <el-input
            v-model="searchKeyword"
            placeholder="请输入角色名称或描述"
            clearable
            style="width: 300px"
            @keyup.enter="handleSearch"
          >
            <template #append>
              <el-button @click="handleSearch">
                <el-icon><Search /></el-icon>
              </el-button>
            </template>
          </el-input>

          <el-button @click="resetSearch" style="margin-left: 10px">
            <el-icon><RefreshRight /></el-icon> 重置
          </el-button>
        </div>
      </div>
    </el-card>

    <el-card class="table-card">
      <el-table :data="tableData" style="width: 100%" border stripe v-loading="loading">
        <!-- <el-table-column prop="id" label="ID" width="180" show-overflow-tooltip /> -->
        <el-table-column prop="name" label="角色名称" width="200" />
        <el-table-column prop="description" label="角色描述" show-overflow-tooltip />
        <el-table-column prop="created_at" label="创建时间" width="180" />
        <el-table-column label="操作" width="150">
          <template #default="scope">
            <div class="action-container">
              <el-tooltip content="编辑" placement="top">
                <el-button
                  class="action-button"
                  type="primary"
                  circle
                  size="small"
                  @click="handleEdit(scope.row)"
                >
                  <el-icon><Edit /></el-icon>
                </el-button>
              </el-tooltip>

              <el-tooltip content="查看用户" placement="top">
                <el-button
                  class="action-button"
                  type="info"
                  circle
                  size="small"
                  @click="viewRoleUsers(scope.row)"
                >
                  <el-icon><User /></el-icon>
                </el-button>
              </el-tooltip>

              <el-tooltip content="删除" placement="top">
                <el-button
                  class="action-button"
                  type="danger"
                  circle
                  size="small"
                  @click="handleDelete(scope.row)"
                >
                  <el-icon><Delete /></el-icon>
                </el-button>
              </el-tooltip>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :total="pagination.total"
          :page-sizes="[10, 20, 30, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 角色表单对话框 -->
    <el-dialog
      :title="roleForm.isAdd ? '新增角色' : '编辑角色'"
      v-model="dialogVisible"
      width="600px"
         :modal="true"
    :append-to-body="true"
    :lock-scroll="true"
      destroy-on-close
    >
      <el-form
        ref="roleFormRef"
        :model="roleForm"
        :rules="roleRules"
        label-width="100px"
        style="max-width: 560px"
      >
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="roleForm.name" placeholder="请输入角色名称" />
        </el-form-item>
        <el-form-item label="角色描述" prop="description">
          <el-input
            v-model="roleForm.description"
            type="textarea"
            :rows="3"
            placeholder="请输入角色描述"
          />
        </el-form-item>
        <el-form-item label="权限列表" prop="permissions" style="display: none">
          <el-tree
            ref="permissionTreeRef"
            :data="permissionTree"
            show-checkbox
            node-key="id"
            :props="{
              label: 'name',
            }"
            default-expand-all
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确认</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 角色用户列表对话框 -->
    <el-dialog
      v-model="userListDialogVisible"
      :title="`角色【${currentRole.name || ''}】分配的用户列表`"
      width="800px"
      destroy-on-close
    >
      <div v-loading="loadingUsers">
        <el-table v-if="roleUsers.length > 0" :data="roleUsers" border stripe style="width: 100%">
          <el-table-column prop="id" label="用户ID" width="180" />
          <el-table-column prop="username" label="用户名" width="150" />
          <el-table-column prop="nickname" label="昵称" width="150" />
        </el-table>
        <el-empty v-else description="该角色暂无分配用户" />
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { Plus, Edit, Delete, Search, RefreshRight, User } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getRoleList, createRole, updateRole, deleteRole, getRoleDetail } from '@/api/role'

// 定义组件名
defineOptions({
  name: 'RoleListPage',
})

// 表格数据
const tableData = ref([])
const loading = ref(false)

// 搜索关键词
const searchKeyword = ref('')

// 分页信息
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0,
})

// 对话框控制
const dialogVisible = ref(false)
const roleFormRef = ref(null)
const permissionTreeRef = ref(null)

// 角色表单数据
const roleForm = reactive({
  id: '',
  name: '',
  description: '',
  permissions: [],
  isAdd: true,
})

// 权限树数据
const permissionTree = ref([
  {
    id: 'system',
    name: '系统管理',
    children: [
      { id: 'system:user:list', name: '用户列表' },
      { id: 'system:user:add', name: '用户新增' },
      { id: 'system:user:edit', name: '用户编辑' },
      { id: 'system:user:delete', name: '用户删除' },
      { id: 'system:role:list', name: '角色列表' },
      { id: 'system:role:add', name: '角色新增' },
      { id: 'system:role:edit', name: '角色编辑' },
      { id: 'system:role:delete', name: '角色删除' },
    ],
  },
  {
    id: 'data',
    name: '数据管理',
    children: [
      { id: 'data:session:list', name: '会话列表' },
      { id: 'data:session:create', name: '创建会话' },
      { id: 'data:session:delete', name: '删除会话' },
      { id: 'data:analysis', name: '数据分析' },
      { id: 'data:report', name: '报告生成' },
    ],
  },
])

// 表单校验规则
const roleRules = {
  name: [
    { required: true, message: '请输入角色名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' },
  ],
}

// 角色用户相关
const userListDialogVisible = ref(false)
const currentRole = ref({})
const roleUsers = ref([])
const loadingUsers = ref(false)

// 获取角色列表
const fetchRoleList = async () => {
  loading.value = true
  // 构建请求参数
  const params = {
    skip: (pagination.currentPage - 1) * pagination.pageSize,
    limit: pagination.pageSize,
  }

  try {
    const res = await getRoleList(params)

    // 检查返回的数据结构
    if (res && res.items && Array.isArray(res.items)) {
      tableData.value = res.items
      pagination.total = res.total || 0
    } else {
      console.error('未能识别API返回的数据结构:', res)
      tableData.value = []
      pagination.total = 0
      ElMessage.error('获取角色列表失败，API返回格式不正确')
    }
  } catch (error) {
    ElMessage.error('获取角色列表失败: ' + (error.message || '未知错误'))
    console.error('获取角色列表失败:', error)
    tableData.value = []
    pagination.total = 0
  } finally {
    loading.value = false
  }
}

// 初始化数据
onMounted(() => {
  fetchRoleList()
})

// 分页大小变化
const handleSizeChange = (val) => {
  pagination.pageSize = val
  fetchRoleList()
}

// 当前页变化
const handleCurrentChange = (val) => {
  pagination.currentPage = val
  fetchRoleList()
}

// 搜索处理
const handleSearch = () => {
  pagination.currentPage = 1
  fetchRoleList()
}

// 重置搜索
const resetSearch = () => {
  searchKeyword.value = ''
  pagination.currentPage = 1
  fetchRoleList()
}

// 新增角色
const handleAdd = () => {
  roleForm.id = ''
  roleForm.name = ''
  roleForm.description = ''
  roleForm.permissions = []
  roleForm.isAdd = true

  // 重置权限树选择
  if (permissionTreeRef.value) {
    permissionTreeRef.value.setCheckedKeys([])
  }

  dialogVisible.value = true
}

// 编辑角色
const handleEdit = async (row) => {
  try {
    // 获取角色详情
    const detail = await getRoleDetail(row.id)

    roleForm.id = detail.id
    roleForm.name = detail.name
    roleForm.description = detail.description
    roleForm.permissions = detail.permissions || []
    roleForm.isAdd = false

    // 设置权限树选择
    if (permissionTreeRef.value) {
      permissionTreeRef.value.setCheckedKeys(detail.permissions || [])
    }

    dialogVisible.value = true
  } catch (error) {
    ElMessage.error('获取角色详情失败: ' + (error.message || '未知错误'))
    console.error('获取角色详情失败:', error)
  }
}

// 删除角色
const handleDelete = (row) => {
  ElMessageBox.confirm(`确定要删除角色【${row.name}】吗？`, '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(async () => {
      try {
        // 调用删除API
        await deleteRole(row.id)
        ElMessage.success('删除成功')
        fetchRoleList()
      } catch (error) {
        ElMessage.error('删除失败: ' + (error.message || '未知错误'))
        console.error('删除角色失败:', error)
      }
    })
    .catch(() => {
      ElMessage.info('已取消删除')
    })
}

// 提交表单
const submitForm = async () => {
  try {
    await roleFormRef.value.validate()

    // 获取选中的权限
    const permissions = permissionTreeRef.value.getCheckedKeys()
    // 添加半选中的父节点
    permissions.push(...permissionTreeRef.value.getHalfCheckedKeys())

    const data = {
      name: roleForm.name,
      description: roleForm.description,
      permissions: permissions,
    }

    if (roleForm.isAdd) {
      // 调用创建角色API
      await createRole(data)
      ElMessage.success('添加成功')
    } else {
      // 调用更新角色API
      await updateRole(roleForm.id, data)
      ElMessage.success('更新成功')
    }

    dialogVisible.value = false
    fetchRoleList()
  } catch (error) {
    ElMessage.error(
      (roleForm.isAdd ? '添加失败' : '更新失败') + ': ' + (error.message || '未知错误'),
    )
    console.error('表单提交失败:', error)
  }
}

// 查看角色用户
const viewRoleUsers = async (row) => {
  try {
    currentRole.value = row
    userListDialogVisible.value = true
    loadingUsers.value = true

    // 获取角色详情，包含用户列表
    const detail = await getRoleDetail(row.id)

    // 检查是否有users数组
    if (detail && detail.users && Array.isArray(detail.users)) {
      roleUsers.value = detail.users
    } else {
      roleUsers.value = []
    }
  } catch (error) {
    ElMessage.error('获取角色用户列表失败: ' + (error.message || '未知错误'))
    console.error('获取角色用户列表失败:', error)
    roleUsers.value = []
  } finally {
    loadingUsers.value = false
  }
}
</script>

<style scoped>
.role-container {
  padding: 20px;
  display: flex;
  flex-direction: column;
  height: calc(100vh - 180px);
  box-sizing: border-box;
}

.operation-card {
  margin-bottom: 20px;
  width: 100%;
}

.operation-area {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
}

.operation-buttons {
  display: flex;
  gap: 10px;
}

.search-container {
  display: flex;
  align-items: center;
}

.table-card {
  flex: 1;
  width: 100%;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

:deep(.el-card__body) {
  height: 100%;
  display: flex;
  flex-direction: column;
}

:deep(.el-table) {
  flex: 1;
  overflow: auto;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 16px;
}

.action-container {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 8px;
}

.action-button {
  font-size: 12px;
  border: none;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
  transition: all 0.3s;
}

.action-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
}
</style>
